package com.byxy.ssm.controller;

import com.byxy.ssm.pojo.Items;
import com.byxy.ssm.service.ItemsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.util.List;

@Controller
@RequestMapping("/items")
public class ItemsController {

    @Resource
    private ItemsService itemsService;

   @GetMapping("/add")
    public String add() {
       return "add";
   }
    @GetMapping("/list")
    public String list(Model model){
      List<Items> items=itemsService.find();
      model.addAttribute("itemsList",items);
        return "list";
    }

    @PostMapping("/upload")
    public String upload(Items items, MultipartFile imgFile, HttpServletRequest req) throws IOException {
       /* Map<String,Object> map=new HashMap<>();*/
         /*  String basePatha1 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        basePatha1 = URLDecoder.decode(basePatha1, "utf-8");
        System.out.println(basePatha1);*/

        String c=System.getProperty("user.dir");
        File realPath=new File(c+"\\src\\main\\resources\\static\\images");
        String fileNmae=imgFile.getOriginalFilename();
        File file=new File(realPath,fileNmae);
        imgFile.transferTo(file);
        items.setImg("/images/" +fileNmae);
        System.out.println(items.getImg());
        itemsService.save(items);
        return "redirect:list";
    }
}
